package com.balarawool.continuations;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

public class ExecutorUtils {

    public static Thread newStopCommandThread(Runnable stopAction) {
        return new Thread(() -> {
            try (BufferedInputStream in = new BufferedInputStream(System.in);
                 InputStreamReader reader = new InputStreamReader(in);
                 LineNumberReader lineNumberReader = new LineNumberReader(reader)) {
                while (true) {
                    String line;
                    try {
                        line = lineNumberReader.readLine();
                        if (line != null) {
                            final String cmd = line.trim();
                            if (cmd.equalsIgnoreCase("stop")
                                    || cmd.equalsIgnoreCase("quit")
                                    || cmd.equalsIgnoreCase("exit")) {
                                stopAction.run();
                                break;
                            }
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }

    public static void shutdownExecutor(ExecutorService executor,
                                        long timeout,
                                        TimeUnit timeUnit) {
        final List<Runnable> queueingTasks = executor.shutdownNow();
        boolean terminated;
        try {
            terminated = executor.awaitTermination(timeout, timeUnit);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if (!queueingTasks.isEmpty()) {
            System.out.println("queued and not executed tasks:");
            queueingTasks.forEach(System.out::println);
        }
        if (!terminated) {
            System.out.println("not terminated");
        }
    }
}
